import { debounce } from './debounce'
// 界面交互
export function wxToast(title) {
  return uni.showToast({
    title: title,
    icon: 'none',
    duration: 3000
  })
}
// 路由
export function wxNavigateTo(url) {
  debounce(uni.navigateTo({
    url,
    fail: () => {
      wxReLaunch(url)
    }
  }), 2000, true)
}
export function wxSwitchTab(url) {
  debounce(uni.switchTab({ url }), 3000, true)
}
export function wxNavigateBack(index) {
  debounce(uni.navigateBack({
    delta: index || 1,
    fail: () => {
      wxSwitchTab('/pages/home/main')
    }
  }), 1000, true)
}
export function wxRedirectTo(url) {
  debounce(uni.redirectTo({
    url,
    fail: () => {
      wxReLaunch(url)
    }
  }), 1000, true)
}

export function wxReLaunch(url) {
  debounce(uni.reLaunch({
    url,
    fail: () => {
      wxRedirectTo(url)
    }
  }), 1000, true)
}

// 缓存
export function setStorage(key, data) {
  uni.setStorageSync(key, data)
}
export function getStorage(key) {
  uni.getStorageSync(key)
}
export function removeStorage(key) {
  wx.removeStorageSync(key)
}
export function clearStorage() {
  uni.clearStorageSync()
}
export function setNavigationBarTitle(title) {
  uni.setNavigationBarTitle({ title })
}
// 支付
export function wxPayApi(params) {
  /* eslint-disable no-new */
  return new Promise((resolve, reject) => {
    uni.requestPayment({
      timeStamp: params.timeStamp,
      nonceStr: params.nonceStr,
      package: params.package,
      signType: 'MD5',
      paySign: params.paySign,
      success: res => {
        console.log(res)
        console.log('支付回到')
        resolve(res)
      },
      fail: err => {
        reject(err)
      }
    })
  })
}
// 是否授权
export function wxGetSetting() {
  return new Promise((resolve) => {
    uni.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          resolve(res)
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称
        } else {
          resolve('')
        }
      }
    })
  })
}
// 微信客服配置
export function openWeChatCustomerService(
  weiXinCustomerServiceUrl = "https://work.weixin.qq.com/kfid/kfc9c8de27dde9c9dbe",
  corpId = "ww060094948b9b7de0",
  showMessageCard = false,
  sendMessageTitle = "",
  sendMessagePath = "",
  sendMessageImg = ""
) {
  if (!weiXinCustomerServiceUrl || !corpId)
    return wxToast("请配置好客服链接或者企业ID")
  uni.openCustomerServiceChat({
    // 客服信息
    extInfo: {
      url: weiXinCustomerServiceUrl, // 客服链接
    },
    corpId, // 企业ID wwed1ca4d3597eXXXX
    showMessageCard, // 是否发送小程序气泡消息
    sendMessageTitle, // 气泡消息标题
    sendMessagePath, // 气泡消息小程序路径（一定要在小程序路径后面加上“.html”，如：pages/index/index.html）
    sendMessageImg, // 气泡消息图片
    success(res) {
      console.log("success", JSON.stringify(res))
    },
    fail(err) {
      console.log("fail", JSON.stringify(err))
    }
  })
}